package com.cskaoyan.controller.admin.polularize;

import com.cskaoyan.exception.ParamsException;
import com.cskaoyan.model.BaseRespVo;
import com.cskaoyan.model.admin.topic.bo.TopicCreateBo;
import com.cskaoyan.model.admin.topic.bo.TopicListBo;
import com.cskaoyan.model.admin.topic.bo.TopicUpdateBo;
import com.cskaoyan.model.admin.topic.vo.TopicBaseRespVo;
import com.cskaoyan.model.admin.topic.vo.TopicReadBaseVo;
import com.cskaoyan.model.admin.pojo.MarketTopicPojo;
import com.cskaoyan.service.admin.popularize.TopicService;
import com.cskaoyan.utils.ValidationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/topic")
public class TopicController {

    @Autowired
    TopicService service;

    @RequestMapping("list")
    public BaseRespVo getTopicList(TopicListBo bo) {
        TopicBaseRespVo respVo = service.getTopicListInfo(bo);
        return BaseRespVo.ok(respVo);
    }

    @RequestMapping("create")
    public BaseRespVo createTopicInfo(@RequestBody @Valid TopicCreateBo bo, BindingResult result) throws ParamsException {
        ValidationUtil.validate(result);

        MarketTopicPojo vo = service.createTopicInfo(bo);
        return BaseRespVo.ok(vo);
    }

    @RequestMapping("read")
    public BaseRespVo readTopicInfo(Integer id) {
        if (id == null) {
            return BaseRespVo.fail("操作失败，请刷新页面重试");
        }

        TopicReadBaseVo result = service.readTopicInfo(id);
        // 异常处理，在查看的时候别人已经删除
        if (result == null) {
            return BaseRespVo.fail("操作失败，请刷新页面重试");
        }

        return BaseRespVo.ok(result);
    }

    @RequestMapping("update")
    public BaseRespVo updateTopicInfo(@RequestBody @Valid TopicUpdateBo bo, BindingResult result) throws ParamsException {
        ValidationUtil.validate(result);
        service.updateTopicInfo(bo);
        return BaseRespVo.ok(bo);
    }

    @RequestMapping("delete")
    public BaseRespVo deleteTopicInfo(@RequestBody Map bo) {
        service.deleteTopicInfo((Integer) bo.get("id"));
        return BaseRespVo.ok("操作成功");
    }

    /**
     *
     * @param request 是一个数组本质
     * @return
     */
    @RequestMapping("batch-delete")
    public BaseRespVo batchDeleteTopicInfo(@RequestBody Map request){
        service.batchDeleteTopicInfo((List<Integer>) request.get("ids"));
        return BaseRespVo.ok("操作成功");
    }
}
